<script setup>
import { ref, onMounted } from 'vue';
import { showToast } from 'vant'; // 引入 Toast

const startTime = ref('');
const endTime = ref('');
const showPicker = ref(false);
const pickerValue = ref([]);
let pickerType = ref('');

const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;

onMounted(() => {
  const now = new Date();
  startTime.value = formatDate(now);
  endTime.value = formatDate(now);
  pickerValue.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
});

const onConfirm = ({ selectedValues }) => {
  const selectedDate = new Date(selectedValues[0], selectedValues[1] - 1, selectedValues[2]);

  if (pickerType.value === 'start') {
    if (selectedDate > new Date(endTime.value)) {
      startTime.value = endTime.value; // 设置开始时间与结束时间一致
      showToast('开始时间不能高于结束时间');
    } else {
      startTime.value = formatDate(selectedDate);
    }
  } else if (pickerType.value === 'end') {
    endTime.value = formatDate(selectedDate);
  }

  pickerValue.value = selectedValues;
  showPicker.value = false;
};

const openPicker = (type) => {
  pickerType.value = type; // 保存当前选择的类型
  showPicker.value = true;
  const dateParts = type === 'start' ? pickerValue.value : pickerValue.value;
  pickerValue.value = dateParts;
};
</script>

<template>
  <van-field
      v-model="startTime"
      is-link
      readonly
      name="start"
      label="开始时间"
      placeholder="点击选择开始时间"
      @click="openPicker('start')"
  />
  <van-field
      v-model="endTime"
      is-link
      readonly
      name="end"
      label="结束时间"
      placeholder="点击选择结束时间"
      @click="openPicker('end')"
  />
  <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
    <van-date-picker
        :model-value="pickerValue"
        @confirm="onConfirm"
        @cancel="showPicker = false"
    />
  </van-popup>
</template>

<style scoped>
</style>